import { reactive } from 'vue'

// 消息类型枚举
export const MessageType = {
  NOTIFICATION: 'notification',  // 实时通知推送
  ALARM: 'alarm',               // 实时告警推送
  HEARTBEAT: 'heartbeat'        // 心跳
} as const

// WebSocket状态管理
const wsState = reactive({
  url: '',
  isConnected: false,
  reconnectAttempts: 0,
  maxReconnectAttempts: 5
})

// 定时器引用
const timers = reactive({
  reconnectInterval: null as number | null,
  heartbeatInterval: null as number | null,
  heartbeatTimeout: null as number | null
})

// 消息处理器映射
const messageHandlers = new Map<string, Function[]>()

// 消息去重机制
const messageDeduplication = {
  lastMessages: new Map<string, { content: string; timestamp: number }>(),
  deduplicationWindow: 2000 // 2秒内的相同消息将被去重
}

// 检查消息是否重复
const isDuplicateMessage = (type: string, messageData: any): boolean => {
  const content = JSON.stringify(messageData)
  const now = Date.now()
  const lastMessage = messageDeduplication.lastMessages.get(type)
  
  if (lastMessage && 
      lastMessage.content === content && 
      (now - lastMessage.timestamp) < messageDeduplication.deduplicationWindow) {
    return true
  }
  
  // 更新最后处理的消息
  messageDeduplication.lastMessages.set(type, { content, timestamp: now })
  return false
}
// 处理接收到的消息
const handleMessage = (event: MessageEvent) => {
  try {
    const data = JSON.parse(event.data)
    console.log('收到消息:', data)

    const type = data.type
    const messageData = data.data

    // 特殊处理心跳响应
    if (type === MessageType.HEARTBEAT) {
      if (timers.heartbeatTimeout) {
        clearTimeout(timers.heartbeatTimeout)
        timers.heartbeatTimeout = null
      }
      return
    }

    // 检查消息是否重复
    if (isDuplicateMessage(type, messageData)) {
      return
    }

    // 执行用户注册的处理器
    const handlers = messageHandlers.get(type)
    if (handlers) {
      handlers.forEach(handler => {
        try {
          handler(messageData)
        } catch (error) {
          console.error('执行消息处理器失败:', error)
        }
      })
    }
  } catch (error) {
    console.error('处理消息失败:', error)
  }
}

// 心跳检测
const startHeartbeat = () => {
  if (timers.heartbeatInterval) {
    clearInterval(timers.heartbeatInterval)
  }

  timers.heartbeatInterval = setInterval(() => {
    if (wsState.isConnected) {
      if (timers.heartbeatTimeout) {
        clearTimeout(timers.heartbeatTimeout)
        timers.heartbeatTimeout = null
      }
      
      sendMessage(MessageType.HEARTBEAT, { timestamp: Date.now() })
      
      timers.heartbeatTimeout = setTimeout(() => {
        handleConnectionError()
      }, 10000)
    }
  }, 60000)
}

// 处理连接错误
const handleConnectionError = () => {
  wsState.isConnected = false
  console.log('WebSocket连接断开，当前重连次数:', wsState.reconnectAttempts)

  // 清理心跳相关定时器
  if (timers.heartbeatInterval) {
    clearInterval(timers.heartbeatInterval)
    timers.heartbeatInterval = null
  }
  if (timers.heartbeatTimeout) {
    clearTimeout(timers.heartbeatTimeout)
    timers.heartbeatTimeout = null
  }

  // 清理消息去重状态
  messageDeduplication.lastMessages.clear()

  // 尝试重连
  if (wsState.reconnectAttempts < wsState.maxReconnectAttempts) {
    reconnect()
  } else {
    console.error('WebSocket重连失败，已达到最大重试次数')
  }
}

// 重连机制
const reconnect = () => {
  wsState.reconnectAttempts++

  timers.reconnectInterval = setTimeout(() => {
    connect(wsState.url)
  }, 3000)
}

// 连接WebSocket
const connect = (url: string): Promise<boolean> => {
  return new Promise((resolve) => {
    try {
      console.log('开始连接WebSocket:', url)
      wsState.url = url
      // @ts-ignore
      uni.connectSocket({
        url: url,
        success: () => {
          console.log('WebSocket连接请求已发送')
        },
        fail: (error: any) => {
          console.error('WebSocket连接请求失败:', error)
          handleConnectionError()
          resolve(false)
        }
      })
      
      // @ts-ignore
      uni.onSocketOpen(() => {
        console.log('WebSocket连接已打开')
        wsState.isConnected = true
        startHeartbeat()
        resolve(true)
      })
      
      // @ts-ignore
      uni.onSocketMessage((event) => {
        handleMessage(event)
      })
      
      // @ts-ignore
      uni.onSocketClose((event) => {
        console.log('WebSocket连接已关闭:', event)
        handleConnectionError()
        resolve(false)
      })
      
      // @ts-ignore
      uni.onSocketError((error) => {
        console.error('WebSocket连接错误:', error)
        handleConnectionError()
        resolve(false)
      })
      
    } catch (error) {
      console.error('创建WebSocket实例失败:', error)
      handleConnectionError()
      resolve(false)
    }
  })
}

// 发送消息
const sendMessage = (type: string, data: any): boolean => {
  if (!wsState.isConnected) {
    console.warn('WebSocket未连接')
    return false
  }

  try {
    const message = {
      type,
      message: data,
      timestamp: Date.now()
    }
    
    // @ts-ignore
    uni.sendSocketMessage({
      data: JSON.stringify(message),
      success: () => {
        console.log('消息发送成功:', type)
      },
      fail: (error: any) => {
        console.error('消息发送失败:', error)
      }
    })
    return true
  } catch (error) {
    console.error('发送消息异常:', error)
    return false
  }
}

// 断开连接
const disconnect = () => {
  if (timers.reconnectInterval) {
    clearTimeout(timers.reconnectInterval)
    timers.reconnectInterval = null
  }

  if (timers.heartbeatInterval) {
    clearInterval(timers.heartbeatInterval)
    timers.heartbeatInterval = null
  }

  // @ts-ignore
  uni.closeSocket({
    success: () => {
      console.log('WebSocket连接已关闭')
    },
    fail: (error: any) => {
      console.error('关闭WebSocket连接失败:', error)
    }
  })

  wsState.isConnected = false
  wsState.reconnectAttempts = 0
  
  // 清理消息去重状态
  messageDeduplication.lastMessages.clear()
}

// 注册消息处理器
const onMessage = (type: string, handler: Function) => {
  if (!messageHandlers.has(type)) {
    messageHandlers.set(type, [])
  }
  messageHandlers.get(type)?.push(handler)
}

// 移除消息处理器
const offMessage = (type: string, handler: Function) => {
  const handlers = messageHandlers.get(type)
  if (handlers) {
    const index = handlers.indexOf(handler)
    if (index > -1) {
      handlers.splice(index, 1)
    }
  }
}

// 清除所有消息处理器
const clearAllMessageHandlers = () => {
  messageHandlers.clear()
  console.log('已清除所有消息处理器')
}

// 导出
export const useWebSocket = () => {
  return {
    wsState,
    connect,
    disconnect,
    sendMessage,
    onMessage,
    offMessage,
    clearAllMessageHandlers
  }
}

